﻿CREATE PROCEDURE [ServiceEngine].[AssignPolicyAssertionToPolicy]
 @PolicyID uniqueidentifier,
 @PolicyAssertionID uniqueidentifier,
 @AssertionOrder smallint
AS
BEGIN
 DECLARE @ErrorMessage NVARCHAR(4000);
 DECLARE @ErrorSeverity INT;
 DECLARE @ErrorState INT;
 SET NOCOUNT ON;

 BEGIN TRY
  BEGIN TRANSACTION  
  
  SELECT AssertionOrder
  FROM ServiceEngine.Policies_PolicyAssertions
  WHERE PolicyAssertionID = @PolicyAssertionID
  AND  PolicyID = @PolicyID
  
  IF (@@ROWCOUNT = 0) 
  BEGIN   
   INSERT ServiceEngine.Policies_PolicyAssertions (PolicyID, PolicyAssertionID, AssertionOrder)
   VALUES (@PolicyID, @PolicyAssertionID, @AssertionOrder)
  END

  COMMIT TRANSACTION
 END TRY
 BEGIN CATCH
  SELECT 
   @ErrorMessage = ERROR_MESSAGE(),
   @ErrorSeverity = ERROR_SEVERITY(),
   @ErrorState = ERROR_STATE();

  IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

  RAISERROR (@ErrorMessage, 
       @ErrorSeverity,
       1);
 END CATCH

END
